package com.mmall.concurrency.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * Created by RID on 2018/4/13.
 */
@Slf4j
public class SemaphoreExample {

    private static int threadCout=20;

    public static void main(String[] args) throws Exception{
        ExecutorService service= Executors.newCachedThreadPool();
        final Semaphore semaphore= new Semaphore(4);
        //final CountDownLatch countDownLatch=new CountDownLatch(threadCout);
        for (int i= 0;i<threadCout;i++){
            final int threadNum=i;
            service.execute(()->{

                try {
                    semaphore.acquire();
                    test(threadNum);
                    semaphore.release();
                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    //countDownLatch.countDown();
                }
            });
        }
        ///countDownLatch.await(10, TimeUnit.MICROSECONDS);
        service.shutdown();
        //log.info("finished");
    }
    private static void test(int tnum)throws Exception{
        Thread.sleep(1000);
        log.info("{}",tnum);
        //Thread.sleep(100);
    }
}
